package com.aiju.cash.ui.member;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.MemberApi;
import com.aiju.cash.ui.member.entity.Member;
import com.aiju.cash.ui.member.entity.MemberCard;
import com.aiju.cash.util.KeywordUtil;
import com.aiju.common.PixValue;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.layout.SettingItemTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2017-02-20 15:59
 * @version: V1.0
 * @Description: 搜索会员
 */
public class MemberSearchActivity extends BaseTitleActivity {

    public static final int SELECT_MEMVER = 2;//选择会员卡


    private EditText mSearchEditText;
    private View mTipView, mDataView, mEmptyView;
    private ListView mListView;

    private int type;

    private List<Member> members;

    private String searchText;

    private String name = "";
    private String phone = "";
    private String mCardId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_user_search);
        setCenterTitle("搜索会员");

        type = getIntent().getIntExtra("type", -1);
        if (getIntent().hasExtra("memberCardId")) {
            mCardId = getIntent().getStringExtra("memberCardId");
        }
        mSearchEditText = (EditText) findViewById(R.id.ev_search_good);
        mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchText = mSearchEditText.getText().toString();
                    if (!TextUtils.isEmpty(searchText)) {
                        mTipView.setVisibility(View.GONE);
                        mDataView.setVisibility(View.VISIBLE);
                        searchGood(searchText);
                    }
                    return true;
                }
                return false;
            }
        });
        mTipView = findViewById(R.id.ly_search_tip);
        mDataView = findViewById(R.id.ly_search_data);

        mEmptyView = findViewById(R.id.tv_search_empty);
        mListView = (ListView) findViewById(R.id.lv_search_good);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (type == SELECT_MEMVER) {
                    Intent mIntent = new Intent(MemberSearchActivity.this, MemberInfoCardsActivity.class);
                    mIntent.putExtra("type", MemberSearchActivity.SELECT_MEMVER);
                    mIntent.putExtra("memberId", members.get(position).getId());
                    startActivityForResult(mIntent, 100);
                }
            }
        });

        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mTipView.setVisibility(View.VISIBLE);
                    mDataView.setVisibility(View.GONE);
                    mEmptyView.setVisibility(View.GONE);
                } else {
                   /* mTipView.setVisibility(View.GONE);
                    mDataView.setVisibility(View.VISIBLE);*/
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (null != data) {
                MemberCard memberCard = (MemberCard) data.getSerializableExtra("memberCard");
                if (memberCard!=null){
                    Intent mIntent = new Intent();
                    mIntent.putExtra("memberCard", memberCard);
                    setResult(100, mIntent);
                    finish();
                }else {
                    Intent intent = new Intent();
                    String memberPhone = data.getStringExtra("memberPhone");
                    intent.putExtra("memberPhone", memberPhone);
                    setResult(100, intent);
                    finish();
                }

            }
        }
    }


    private void searchGood(String s) {
        mDialogHelper.showLoadingProgressDialog();
/*        if (CheckUtil.isNumeric(s.toString())) {
            phone = s;
            name = "";
        } else {
            phone = "";
            name = s;
        }*/
        new MemberApi().getByCondition(mUser.getToken(), mUser.getStoreId(), s, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();

                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    members = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<List<Member>>() {
                    }.getType());

                    if (Util.isEmpty(members)) {
                        mDataView.setVisibility(View.GONE);
                        mEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        mListView.setAdapter(new MyBaseAdapter(MemberSearchActivity.this, members));
                    }
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    class MyBaseAdapter extends BaseAdapter {

        private List<Member> cards;

        private Context context;

        public MyBaseAdapter(Context context, List<Member> cards) {
            this.context = context;
            this.cards = cards;
        }

        @Override
        public int getCount() {
            return cards.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Member member = cards.get(position);
            SettingItemTextView textView = new SettingItemTextView(context);
            textView.getRightView().setTextColor(Color.parseColor("#666666"));

            SpannableString right = KeywordUtil.matcherSearchTitle(
                    getResources().getColor(R.color.app_display_color), member.getPhone(), searchText);

            SpannableString left = KeywordUtil.matcherSearchTitle(
                    getResources().getColor(R.color.app_display_color), member.getName(), searchText);

            textView.getleftView().setText(left);
            textView.getRightView().setText(right);
            textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, PixValue.dp.valueOf(44)));
            return textView;
        }
    }
}
